package com.xqb.listen.manager

import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import com.xqb.listen.IApp
import com.xqb.listen.manager.media.model.MediaModel
import com.xqb.listen.model.PlayStatus
import com.xqb.listen.service.MusicForegroundService
import kotlinx.coroutines.flow.MutableStateFlow

/**
 * @author Ling
 * @date :2025/3/12 9:43
 */
class MediaPlayManager {

    companion object{
        @JvmStatic
        val singleInstance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { MediaPlayManager() }
    }

    private lateinit var mediaPlayer: MediaPlayer


    var currentMedia : MediaModel? = null
    var currentState = MutableStateFlow(PlayStatus.INIT.name)

    fun initMediaPlayer(context: Context){
        try {
            if(::mediaPlayer.isInitialized){
                mediaPlayer.reset()
                return
            }
            mediaPlayer = MediaPlayer()
            mediaPlayer.setOnCompletionListener {
                currentState.value = PlayStatus.FINISH.name
                updateForegroundStatus(context , PlayStatus.FINISH)
            }
            mediaPlayer.setOnPreparedListener {
                it.start()
                currentState.value = PlayStatus.PLAY.name
                updateForegroundStatus(context , PlayStatus.PLAY)
            }
            mediaPlayer.setOnErrorListener { _, _, _ ->
                currentState.value = PlayStatus.ERROR.name
                updateForegroundStatus(context , PlayStatus.ERROR)
                mediaPlayer.reset()
                println("--->player init error")
                false
            }
        } catch (e: Exception) {
            currentState.value = PlayStatus.ERROR.name
            updateForegroundStatus(context , PlayStatus.ERROR)
            mediaPlayer.reset()
            println("--->player play crash")
        }
    }

    fun destroyPlayer(){
        try {
            if(::mediaPlayer.isInitialized){
                mediaPlayer.pause()
                mediaPlayer.stop()
                mediaPlayer.release()
            }
        } catch (e: Exception) {
            println("--->player destroy error")
        }
    }

    fun initAudio(context: Context, updateForeground : Boolean, mediaModel: MediaModel?){
        //如果当前有正在播放的音乐，而设置播放的音乐又为空直接跳过，否则会把当前在播的给中断掉
        if(currentMedia != null && mediaModel == null) return
        try {
            currentMedia = mediaModel
            if(::mediaPlayer.isInitialized){
                mediaPlayer.reset()
            }
            currentState.value = PlayStatus.INIT.name
            if(updateForeground){
                updateForegroundStatus(context , PlayStatus.INIT)
            }
            if(mediaModel != null){
                if(::mediaPlayer.isInitialized){
                    mediaPlayer.setDataSource(mediaModel.filepath)
                    mediaPlayer.prepareAsync()
                }
            }

        } catch (e: Exception) {
            if (::mediaPlayer.isInitialized) {
                mediaPlayer.reset()
            }
            if(updateForeground){
                updateForegroundStatus(context , PlayStatus.PAUSE)
            }
            println("--->player play crash")
        }
    }

    fun updateForegroundStatus(context: Context , playStatus: PlayStatus){
        try {
            val intent  = Intent(IApp.mContext, MusicForegroundService::class.java)
            intent.action = playStatus.name
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                context.startForegroundService(intent)
            }else{
                context.startService(intent)
            }
        } catch (e: Exception) {
            println("---> ${e.message}")
        }
    }

    fun resumeAudio(context: Context , updateForeground : Boolean){
        try {
            if (::mediaPlayer.isInitialized) {
                mediaPlayer.start()
            }
            currentState.value = PlayStatus.PLAY.name
            if(updateForeground){
                updateForegroundStatus(context , PlayStatus.PLAY)
            }
        } catch (e: Exception) {
            if (::mediaPlayer.isInitialized) {
                mediaPlayer.reset()
            }
            if(updateForeground){
                updateForegroundStatus(context , PlayStatus.PAUSE)
            }
            println("--->player play crash")
        }
    }

    fun pauseAudio(context: Context , updateForeground : Boolean){
        try {
            if (::mediaPlayer.isInitialized) {
                mediaPlayer.pause()
            }
            currentState.value = PlayStatus.PAUSE.name
            if(updateForeground){
                updateForegroundStatus(context , PlayStatus.PAUSE)
            }
        } catch (e: Exception) {
            if (::mediaPlayer.isInitialized) {
                mediaPlayer.reset()
            }
            if(updateForeground){
                updateForegroundStatus(context , PlayStatus.PAUSE)
            }
            println("--->player pause crash")
        }
    }
}